//devices.js
const {jump,toast,getPageInstance,query2obj} = require('../../utils/util');
const {bluetoothAdapterState} = require('../../utils/bluetooth');
const {Event} = require('../../utils/constant');
const app = getApp();
Page({
  data: {},
  onLoad: function () {
    const that = this;
    app.event.on(Event.BluetoothAdapterStateChange, that.BluetoothAdapterStateChangeHandler, that);


  },
  onUnload:function(){
    app.event.off(Event.BluetoothAdapterStateChange, this.BluetoothAdapterStateChangeHandler);
  },
  BluetoothAdapterStateChangeHandler:function(){
    this.rescan();
  },
  rescan: function () {

    const that = this;
    wx.getBluetoothAdapterState({
      success:function (res) {
        const {discovering,available} = res;
        if(!available){
          wx.showToast({title: '请打开蓝牙', icon: 'none'});
        }else{
          that.scanCode();
        }

      },
      fail:function (res) {
        wx.showToast({title: '请打开蓝牙', icon: 'none'});
      }
    });


  },
  scanCode: function () {

    setTimeout(function () {
      // 允许从相机和相册扫码
      wx.scanCode({
        onlyFromCamera: true,
        success: function (res) {

          const {result, scanType, charSet, path} = res;
          const {id} = query2obj(result);
          if(id){
            jump({pageName: 'searchBySerialNumber', params: {id}, type: 0});
          }else{
            // jump({pageName:'scanIncorrectCode',type:0});
          }
        },
        fail: function () {

        }
      })
    },300);

  },
});
